import { DataSource } from 'typeorm';
import { User, UserStatus } from '../../../entities/user.entity';
import * as crypto from 'crypto';

// 替代 bcrypt 的简单哈希函数
function hashPassword(password: string): string {
  return crypto.createHash('sha256').update(password).digest('hex');
}

/**
 * 用户种子数据
 * 负责初始化基本用户
 */
export class UserSeed {
  constructor(private dataSource: DataSource) {}

  /**
   * 运行用户种子
   */
  async run(): Promise<void> {
    console.log('开始初始化用户数据...');

    const userRepository = this.dataSource.getRepository(User);

    // 系统默认用户
    const defaultUsers = [
      {
        username: 'admin',
        password: 'admin123',
        email: 'admin@example.com',
        status: UserStatus.ACTIVE
      },
      {
        username: 'user',
        password: 'user123',
        email: 'user@example.com',
        status: UserStatus.ACTIVE
      },
      {
        username: 'guest',
        password: 'guest123',
        email: 'guest@example.com',
        status: UserStatus.ACTIVE
      }
    ];

    // 创建默认用户
    for (const userData of defaultUsers) {
      // 检查用户是否已存在
      const existingUser = await userRepository.findOneBy({
        username: userData.username
      });

      if (!existingUser) {
        // 使用简单哈希函数加密密码
        const hashedPassword = hashPassword(userData.password);
        
        // 创建用户
        const user = userRepository.create({
          ...userData,
          password: hashedPassword
        });
        
        await userRepository.save(user);
        console.log(`创建用户: ${user.username}`);
      } else {
        console.log(`用户已存在: ${existingUser.username}`);
      }
    }

    console.log('用户数据初始化完成');
  }
} 